#include "led.h"

Led::Led(const string path, const vector< uint8_t > nums, const uint8_t state) {
    uint8_t buf[2] = {0, 0};
    size_t i, size = nums.size();
    // 初始化数据
    this->fd = -1;
    // 打开led
    if ((this->fd = open(path.c_str(), O_RDWR)) == -1)
        throw runtime_error("open '" + path + "' error!\n");
    // 初始化灯状态
    for (i = 0; i < size; i++) {
        this->states[nums[i]] = state;
        buf[0] = state, buf[1] = nums[i];
        write(fd, buf, sizeof(buf));
    }
}

Led::~Led() {
    // 关闭文件
    if (this->fd != -1)
        close(this->fd);
}

uint32_t &Led::get_state(const uint8_t num) {
    // 查找状态
    if (this->states.find(num) == this->states.end()) {
        this->state = 0xffffffff;
        return this->state;
    }
    this->state = this->states[num];
    return this->state;
}

Led &Led::set_state(const uint8_t num, const uint8_t state) {
    uint8_t buf[2] = {state, num};
    if (this->states.find(num) == this->states.end())
        return *this;
    // 修改状态
    this->states[num] = state;
    //  设置状态
    write(this->fd, buf, sizeof(buf));
    return *this;
}